package com.offcn.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.xml.crypto.Data;
import java.util.Date;

public class JWTUtil {
    //密钥
    public static final String SECRET_KEY = "u-member-offcn123";
   //token过期时间
    public static final  long  TOKEN_EXPIRE_TIME = 5 * 60 * 1000;
    //refreshToken过期时间
    public static  final  long REFRESH_TOKEN_EXPIRE_TIME = 10 * 60 * 1000;
    private static final String ISSUER = "offcn";//签发人
    //生产token
    public static String generateToken(String username){
        Date date = new Date();
        //通过加密算法获取token
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        String token = JWT.create()
                .withIssuer(ISSUER)    //签发人
                .withIssuedAt(date)     //
                .withExpiresAt(new Date(date.getTime() + TOKEN_EXPIRE_TIME))  //过期时间
                .withClaim("username", username)    //用户名
                .sign(algorithm);         //指定算法
        return token;
    }


     //验证签名
    public static boolean verify(String token){
        try {
            //指定加密算法
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
            //创建验证签名对象
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build();
            //验证签名
            verifier.verify(token);
            return true;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        }
        return false;
    }
    //通过token获取用户名
    public static String getUsername(String token){
        String username = JWT.decode(token).getClaim("username").asString();
        return username;
    }

}
